package com.dmz.czykt.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dmz.common.utils.secure.GMUtil;
import com.dmz.czykt.config.Constants;
import com.dmz.czykt.service.CzyktService;
import com.dmz.czykt.util.CzyktSftpFileUtil;
import com.dmz.czykt.util.EncryptUtil;
import com.dmz.czykt.util.HttpClient;
import com.dmz.czykt.util.SocketClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author lee
 */

@Service
@Slf4j
public class CzyktServiceImpl implements CzyktService {

    //获取sftp用户名
    @Value("${sftpUserName}")
    private String sftpUserName;
    //获取sftp密码
    @Value("${sftpPasswd}")
    private String sftpPasswd1;
    //获取sftpip
    @Value("${sftpIP}")
    private String sftpIP;
    //获取sftp端口
    @Value("${sftpPort}")
    private int sftpPort;
    //获取sftp下载地址
//    @Value("${sftpDownPath:/BOCbank/}")
//    private String saveDmzFile;
   // 本地路径
//    @Value("${localPath:/home/cspj/dmz/czykt/file/local/}")
//    private String saveFile;
    //本地路径
//    @Value("${localOutPath:/home/cspj/dmz/czykt/file/out/}")
//    private String outPathFile;
    //获取sftp上传路径
//    @Value("${sftpDir:/BOCbank/}")
//    private String sftpDir;
    //获取sftp上传路径
    @Value("${key}")
    private String key;
    //url
    @Value("${url}")
    private String url;
    @Value("${size}")
    private int size;
    @Value("${cspIp}")
    private String cspIp;
    @Value("${cspPort}")
    private String port;

    @Value("${bpsftpUserName}")
    private String bpsftpUserName1;
    @Value("${bpsftpPasswd}")
    private String bpsftpPasswd1;
    @Value("${bpsftpIP}")
    private String bpsftpIP;
    @Value("${bpsftpDir:/tc/czykt/upload/}")
    private String bpsftpDir;
    @Value("${bpsftpPort}")
    private int bpsftpPort;
    @Value("${bpsIp}")
    private String bpsIp;
    @Value("${bpsPort}")
    private int bpsPort;

    @Value("${sm4.key}")
    private String sm4key;

    @Value("${sm4.iv}")
    private String iv;

    @Override
    public String getYH010Info(String fileName, String outpath, JSONObject param) {
        StringBuilder infos = new StringBuilder();
        log.info("getYH010Info:: outpath::{}", outpath);
        InputStreamReader isr;
        int zbs = 0;
        int rowCnt = 0;
        int sucRowCnt = 0;
        String resjson = "";

        try {
            isr = new InputStreamReader(Files.newInputStream(FileUtil.newFile(fileName).toPath()), "UTF-8");
            BufferedReader buf = new BufferedReader(isr);
            String str;
            List<Map<String, String>> data = new ArrayList<Map<String, String>>();

            while ((str = buf.readLine()) != null) {
                str = str.replaceAll("\\|", "");
                str = str.replaceAll("\\@", "");
                System.out.println(str);
                String[] strs = str.split("\\$", -1);
                Map<String, String> map = new HashMap<>();
                map.put("mxlsh", strs[0]);
                map.put("name", strs[1]);
                map.put("idNo", strs[2]);
                map.put("bankAcct", strs[3]);
                map.put("extend1", strs[4]);
                map.put("extend2", strs[5]);
                data.add(map);
            }

            zbs = (data.size() % size == 0 ? data.size() / size : data.size() / size + 1);
            for (int i = 1; i <= zbs; i++) {
                System.out.println(i);
                int gs = 0;
                if (i != 1) {
                    i = i - 1;
                    gs = size * i;
                    i++;
                }
                List<Map<String, String>> datanew = new ArrayList<Map<String, String>>();
                for (int k = gs; k < size * i; k++) {
                    if (k == data.size()) {
                        break;
                    }
                    datanew.add(data.get(k));
                }
                List<Map<String, String>> head = new ArrayList<Map<String, String>>();
                Map<String, String> headMap = new HashMap<>();
                headMap.put("size", "" + datanew.size());
                headMap.put("id", "YH010");
                head.add(headMap);
                JSONObject jo = JSONUtil.createObj()
                        .accumulate("head", headMap)
                                .accumulate("data", datanew);
                log.info("发送csp内容后的信息{}", jo.toString());
                SocketClientUtil tc = new SocketClientUtil(cspIp, Integer.parseInt(port));
                String sendMsg = jo.toString();
                String length = SocketClientUtil.padding(sendMsg.getBytes("utf-8").length + "", 7, "0", "L");
                String sendMsgSend = length + sendMsg;
                tc.send(sendMsgSend);
                resjson = tc.receive();
                String[] result = resjson.split("\\&", -1);
                rowCnt += Integer.parseInt(result[0]);
                sucRowCnt += Integer.parseInt(result[1]);
                resjson = resjson.substring(resjson.lastIndexOf("&") + 1);
                infos.append(resjson);


            }

            JSONObject headjo = param.getJSONObject("head");
            outpath = outpath + "bt009_" + headjo.getStr("callUser") + "_" + headjo.getStr("bankNo") + "To" + headjo.getStr("areaCode") + "_" + headjo.getStr("uuid") + ".txt";
            //读文件
            File f = FileUtil.newFile(outpath);
            //创建流（拿个笔）
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "GB18030"));
            //写文件内容
            output.write(infos.toString());
            //关闭流 （把笔放了）
            output.close();

            log.info("file write success{}", outpath);
            return "{\"rowCnt\":\"" + rowCnt + "\",\"sucRowCnt\":\"" + sucRowCnt + "\",\"outpath\":\"" + outpath.substring(outpath.lastIndexOf(File.separator) + 1) + "\"}";
            //发送csp


        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage(), e);
        }
        return null;
    }


    @Override
    public String getYH005Info(String fileName) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getBT006Info(String fileName) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void acceptValidatedDetail(String fileName, JSONObject param) throws Exception {
        //获取sftp用户名
        //String sftpuser = sftpUserName;
        String sftpuser = GMUtil.db(sm4key, iv, sftpUserName);
        //获取sftp密码
        //String sftpPasswd = sftpPasswd1;
        String sftpPasswd = GMUtil.db(sm4key, iv, sftpPasswd1);
        CzyktSftpFileUtil sftp = new CzyktSftpFileUtil();
        String saveDmzFile = Constants.sftpDownPath;
        String saveFile = Constants.localPath;
        String outPathFile = Constants.localOutPath;
        String sftpDir = Constants.sftpDir;
        String bpsftpDir = Constants.bpsftpDir;
        //下载sftp文件
        boolean flag = sftp.ConnectDownload(sftpuser, sftpPasswd, sftpIP, sftpPort, saveDmzFile, fileName, saveFile + fileName);
        //测试用
// 		boolean flag =sftpFileUtil.DownFile(fileName, map);// sftpFileUtil.ConnectDownload(sftpuser,sftpPasswd,sftpIP,sftpPort, saveDmzFile, fileName,saveFile+fileName);//下载sftp文件
        if (flag) {
            log.info(" yh010下载 SFTP down ok:{}{}", saveFile, fileName);
            //解密后明文转U8格式
            boolean enflag = EncryptUtil.readTxtYH010de(saveFile + fileName, key);
            if (enflag) {

                //发csp用U8 返回后用GB18030
                String resultjson = getYH010Info(saveFile + fileName, outPathFile, param);
                log.info(resultjson);
                JSONObject resJo = JSONUtil.parseObj(resultjson);

                String rowCnt = resJo.getStr("rowCnt");
                String sucRowCnt = resJo.getStr("sucRowCnt");
                outPathFile = outPathFile + resJo.getStr("outpath");
                log.info("-----outPathFile:{}", outPathFile);
                String outfileName = outPathFile.substring(outPathFile.lastIndexOf(File.separator) + 1);
                EncryptUtil.encryptEcbTxt(outPathFile, key);
                log.info("上传文件：" + outPathFile);
                //上传bps
//                String bpsftpUserName = bpsftpUserName1;
//                String bpsftpPasswd = bpsftpPasswd1;
                String bpsftpUserName = GMUtil.db(key, iv, bpsftpUserName1);
                String bpsftpPasswd = GMUtil.db(key, iv, bpsftpPasswd1);
                boolean bpsFlag = CzyktSftpFileUtil.uploadFile(outPathFile, bpsftpUserName, bpsftpPasswd, bpsftpIP, bpsftpPort, bpsftpDir);
                if (bpsFlag) {
                    System.out.println("BT009 上传 bps upload:ok" + outPathFile);
                    log.info(" BT009 上传 bps upload:ok{}", outPathFile);

//					boolean flagup = true;
                    boolean flagup = sftp.ConnectUpload(sftpuser, sftpPasswd, sftpIP, sftpPort, sftpDir, outPathFile);
                    if (flagup) {
                        log.info(" yh010 上传sftp upload:ok{}", outPathFile);
                        //通知第三方
                        JSONObject headjo = param.getJSONObject("head");
                        String json = "{\"head\":{\"id\":\"BT009\",\"uuid\":\"" + headjo.getStr("uuid") + "\",\"callDate\":\"" + headjo.getStr("callDate") + "\",\"callTime\":\"" + headjo.getStr("callTime") + "\",\"callUser\":\"" + headjo.getStr("callUser") + "\",\"areaCode\":\"" + headjo.getStr("areaCode") + "\",\"bankNo\":\"" + headjo.getStr("bankNo") + "\"},\"data\":{\"rowCnt\":\"" + rowCnt + "\",\"sucRowCnt\":\"" + sucRowCnt + "\",\"fileName\":\"" + outfileName + "\", \"extend1\":\"\",\"extend2\":\"\"}}";
                        try {
                            HttpClient.doPost2(url, json);
                        } catch (Exception e) {
                            log.error("发送http报文失败{}", e.getMessage(), e);
                        }
                    } else {
                        log.info(" yh010上传sftp  upload:no{}", outPathFile);
                    }
                } else {
                    log.info(" yh010 上传 bps upload:no{}", outPathFile);
                }
            }
        } else {
            log.info(" yh010 上传 bps upload:no{}", outPathFile);
        }
    }

    @Override
    public String acceptData(String fileName, JSONObject param) throws Exception {
        //获取sftp用户名
        //String sftpuser = sftpUserName;
        String sftpuser = GMUtil.db(sm4key, iv, sftpUserName);
        //获取sftp密码
        //String sftpPasswd = sftpPasswd1;
        String sftpPasswd = GMUtil.db(sm4key, iv, sftpPasswd1);
        String result = "";
        try {
            CzyktSftpFileUtil sftp = new CzyktSftpFileUtil();
            //下载sftp文件
            String saveDmzFile = Constants.sftpDownPath;
            String saveFile = Constants.localPath;
            String bpsftpDir = Constants.bpsftpDir;
            boolean flag = sftp.ConnectDownload(sftpuser, sftpPasswd, sftpIP, sftpPort, saveDmzFile, fileName, saveFile + fileName);
//			boolean flag =sftpFileUtil.DownFile(fileName, map);//测试用
            if (flag) {
                log.info(" yh005下载 SFTP down ok:{}{}", saveFile, fileName);
                //解密后明文
                boolean enflag = EncryptUtil.readTxtYH010de(saveFile + fileName, key);
                if (enflag) {
                    //上传bps
//                    String bpsftpUserName = bpsftpUserName1;
//                    String bpsftpPasswd = bpsftpPasswd1;
                    String bpsftpUserName = GMUtil.db(key, iv, bpsftpUserName1);
                    String bpsftpPasswd = GMUtil.db(key, iv, bpsftpPasswd1);
                    boolean bpsFlag = CzyktSftpFileUtil.uploadFile(saveFile + fileName, bpsftpUserName, bpsftpPasswd, bpsftpIP, bpsftpPort, bpsftpDir);
                    if (bpsFlag) {
                        //发送bps文件 通知 报文是数线分隔
                        SocketClientUtil tc = new SocketClientUtil(bpsIp, bpsPort);

                        JSONObject head = param.getJSONObject("head");
                        JSONObject data = param.getJSONObject("data");
                        String sendMsg = head.get("id") + "|" + head.get("uuid") + "|" + head.get("callDate") + "|" + head.get("callTime") + "|" + head.get("callUser") + "|" + head.get("areaCode") + "|" + head.get("bankNo") + "|"
                                + "|" + data.get("payeeAcctNo") + "|" + data.getStr("payeeAcctName") + "|" + data.getStr("payeeAcctDep") + "|" + data.getStr("projName") + "|" + data.getStr("amtSum")
                                + "|" + data.getStr("rowCnt") + "|" + data.get("fileName") + "|" + data.get("extend4")
                                + "|" + data.get("extend5") + "|" + data.get("extend6") + "|";
                        tc.send(sendMsg);
                        result = tc.receive();
                        log.info(" yh005 上传 bps upload:ok");
                    } else {
                        log.info(" yh005 上传 bps upload:no{}", saveFile);
                    }
                }
            } else {
                log.info(" yh005 上传 bps upload:no{}", saveFile);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


    @Override
    public String getBT009Info(String fileName, Map<String, String> map) {
        // TODO Auto-generated method stub
        return null;
    }


}
